/**
 * 研发项目模块控制器
 */
const { BaseController } = require('../config/libs_config');
const { cloudHelper, timeHelper, pageHelper } = require('../config/project_helpers_config');
const ResearchService = require('../service/research_service.js');
const ResearchResourceService = require('../service/research_resource_service.js');
const ResearchBranchService = require('../service/research_branch_service.js');
const { ResearchStateBiz } = require('../config/biz_config');
const { dataHelper } = require('../config/project_helpers_config');
const { researchBiz } = require('../config/biz_config');
const { UserModel, AdminModel, ResearchProjectModel } = require('../config/models_config');
const ProjectDataBiz = require('../config/biz_config').ProjectDataBiz;
const ResearchBiz = require('../comm/biz/research_biz.js');
const ResearchProjectBiz = require('../comm/biz/research_project_biz.js');

class ResearchController extends BaseController {

	/**
	 * 构造函数
	 */
	constructor() {
		super();
		this._service = new ResearchService();
		this._resourceService = new ResearchResourceService();
		this._branchService = new ResearchBranchService();
	}

	/**
	 * 获取项目列表页面
	 * @param {*} e 
	 */
	async getResearchListPage(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.pageErrorAuth(err.message);
		}

		// 获取数据
		let params = {
			search: '',
			sortType: '',
			sortVal: '',
			status: '',
			activeStatus: '',
			cate: '',
			page: 1,
			size: 20
		};

		// 初始化列表
		const result = await this._service.getResearchList(params);

		// 获取列表状态统计
		const statusStats = ResearchStateBiz.getProjectStatusStats(result.list);
		
		return this.render('projects/plm/pages/project/list/project_list', {
			list: result.list,
			total: result.total,
			statusStats,
			params
		});
	}

	/**
	 * 项目列表数据
	 * @param {*} e 
	 */
	async getResearchList(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 获取数据
		let params = {
			search: e.query.search || '',
			sortType: e.query.sortType || '',
			sortVal: e.query.sortVal || '',
			status: e.query.status || '',
			activeStatus: e.query.activeStatus || '',
			cate: e.query.cate || '',
			page: e.query.page || 1,
			size: e.query.size || 20
		};

		// 获取列表
		const result = await this._service.getResearchList(params);

		// 获取列表状态统计
		const statusStats = ResearchStateBiz.getProjectStatusStats(result.list);

		return this.appReturn({
			list: result.list,
			total: result.total,
			statusStats,
			params
		});
	}

	/**
	 * 获取项目详情
	 * @param {*} e 
	 */
	async getResearchDetail(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.id) {
			return this.appError('项目ID不能为空');
		}

		const id = e.query.id;

		// 获取项目
		const project = await this._service.getResearchDetail(id);
		if (!project) {
			return this.appError('项目不存在');
		}

		return this.appReturn(project);
	}

	/**
	 * 获取项目详情页面
	 * @param {*} e 
	 */
	async getResearchDetailPage(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.pageErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.id) {
			return this.pageError('项目ID不能为空');
		}

		const id = e.query.id;

		// 获取项目
		const project = await this._service.getResearchDetail(id);
		if (!project) {
			return this.pageError('项目不存在');
		}

		// 使用ProjectDataBiz获取状态名称
		project.statusName = ProjectDataBiz.getStatusName(project.PROJECT_STATUS);
		if (project.PROJECT_STATUS >= 10 && project.PROJECT_STATUS < 99) {
			project.activeStatusName = ProjectDataBiz.getActiveStatusName(
				project.PROJECT_ACTIVE_STATUS
			);
		}

		// 获取项目可流转状态
		const stateTransitions = ResearchStateBiz.getStateTransitionStructure(
			project.PROJECT_STATUS,
			project.PROJECT_ACTIVE_STATUS
		);

		// 获取项目资源列表
		const resources = await this._resourceService.getResourceList(id);

		// 获取项目父项目
		const parentProject = await this._branchService.getParentProject(id);

		// 获取项目分支列表
		const branches = await this._branchService.getBranchList(id);

		// 获取项目流转历史
		const flowHistory = await this._service.getResearchFlowHistory(id);

		return this.render('projects/plm/pages/project/detail/project_detail', {
			project,
			stateTransitions,
			resources: resources.list,
			resourceTotal: resources.total,
			parentProject,
			branches: branches.list,
			branchTotal: branches.total,
			flowHistory: flowHistory.list,
			flowTotal: flowHistory.total
		});
	}

	/**
	 * 获取项目图谱页面
	 * @param {*} e 
	 */
	async getResearchGraphPage(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.pageErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.id) {
			return this.pageError('项目ID不能为空');
		}

		const id = e.query.id;

		// 获取项目
		const project = await this._service.getResearchDetail(id);
		if (!project) {
			return this.pageError('项目不存在');
		}

		return this.render('projects/plm/pages/project/graph/research_graph', {
			project
		});
	}

	/**
	 * 获取项目图谱数据
	 * @param {*} e 
	 */
	async getProjectGraph(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.projectId) {
			return this.appError('项目ID不能为空');
		}

		const projectId = e.query.projectId;
		const showBranch = e.query.showBranch !== 'false';
		const showFlow = e.query.showFlow !== 'false';

		// 获取项目图谱
		const graph = await this._service.getResearchGraph(projectId, showBranch, showFlow);
		if (!graph) {
			return this.appError('获取项目图谱失败');
		}

		return this.appReturn(graph);
	}

	/**
	 * 项目状态流转
	 * @param {*} e 
	 */
	async transitProjectState(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.projectId) {
			return this.appError('项目ID不能为空');
		}

		if (e.query.status === undefined || e.query.status === null) {
			return this.appError('目标状态不能为空');
		}

		const projectId = e.query.projectId;
		const toStatus = parseInt(e.query.status);
		const toActiveStatus = e.query.activeStatus !== undefined && e.query.activeStatus !== null ? 
			parseInt(e.query.activeStatus) : 0;

		// 流转数据
		const flowData = {
			note: e.query.note || '',
			docs: e.query.docs || [],
			tags: e.query.tags || []
		};

		// 状态流转
		const result = await ResearchStateBiz.transitProjectState(
			projectId, 
			toStatus, 
			toActiveStatus, 
			flowData
		);

		if (result.code !== 0) {
			return this.appError(result.message);
		}

		return this.appReturn();
	}

	/**
	 * 创建项目分支
	 * @param {*} e 
	 */
	async createProjectBranch(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.parentId || !e.query.branchNodeId) {
			return this.appError('父项目ID和分支节点ID不能为空');
		}

		const parentId = e.query.parentId;
		const branchNodeId = e.query.branchNodeId;
		const branchName = e.query.branchName || '';
		const branchDesc = e.query.branchDesc || '';

		// 创建分支
		const result = await this._branchService.createBranch(
			parentId, 
			branchNodeId, 
			branchName, 
			branchDesc
		);

		if (!result) {
			return this.appError('创建分支失败');
		}

		return this.appReturn(result);
	}

	/**
	 * 合并项目分支
	 * @param {*} e 
	 */
	async mergeProjectBranch(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.branchId) {
			return this.appError('分支项目ID不能为空');
		}

		const branchId = e.query.branchId;
		const mergeNote = e.query.mergeNote || '';

		// 合并分支
		const result = await this._branchService.mergeBranch(branchId, mergeNote);

		if (!result) {
			return this.appError('合并分支失败');
		}

		return this.appReturn(result);
	}

	/**
	 * 获取项目资源列表
	 * @param {*} e 
	 */
	async getResourceList(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.projectId) {
			return this.appError('项目ID不能为空');
		}

		const projectId = e.query.projectId;
		const resourceType = e.query.resourceType !== undefined && e.query.resourceType !== null ? 
			parseInt(e.query.resourceType) : null;
		const page = e.query.page || 1;
		const size = e.query.size || 20;

		// 获取资源列表
		const result = await this._resourceService.getResourceList(
			projectId, 
			resourceType, 
			page, 
			size
		);

		return this.appReturn(result);
	}

	/**
	 * 获取资源版本列表
	 * @param {*} e 
	 */
	async getVersionList(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.resourceId) {
			return this.appError('资源ID不能为空');
		}

		const resourceId = e.query.resourceId;
		const page = e.query.page || 1;
		const size = e.query.size || 20;

		// 获取版本列表
		const result = await this._resourceService.getVersionList(resourceId, page, size);

		return this.appReturn(result);
	}

	/**
	 * 创建资源
	 * @param {*} e 
	 */
	async createResource(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.projectId || !e.query.resourceName || e.query.resourceType === undefined) {
			return this.appError('项目ID、资源名称和资源类型不能为空');
		}

		// 构建数据
		const data = {
			PROJECT_ID: e.query.projectId,
			PROJECT_TITLE: e.query.projectTitle || '',
			RESOURCE_NAME: e.query.resourceName,
			RESOURCE_TYPE: parseInt(e.query.resourceType),
			RESOURCE_DESC: e.query.resourceDesc || '',
			VERSION: e.query.version || 'v1.0.0',
			VERSION_DESC: e.query.versionDesc || '初始版本',
			VERSION_DATA: e.query.versionData || {},
			IS_RELEASE: e.query.isRelease === 'true'
		};

		// 创建资源
		const result = await this._resourceService.createResource(data);

		if (!result) {
			return this.appError('创建资源失败');
		}

		return this.appReturn(result);
	}

	/**
	 * 创建资源版本
	 * @param {*} e 
	 */
	async createVersion(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.resourceId || !e.query.version) {
			return this.appError('资源ID和版本号不能为空');
		}

		// 获取资源
		const resource = await this._resourceService.getResourceDetail(e.query.resourceId);
		if (!resource) {
			return this.appError('资源不存在');
		}

		// 构建数据
		const data = {
			RESOURCE_ID: resource._id,
			RESOURCE_NAME: resource.RESOURCE_NAME,
			RESOURCE_TYPE: resource.RESOURCE_TYPE,
			VERSION: e.query.version,
			VERSION_DESC: e.query.versionDesc || '',
			VERSION_DATA: e.query.versionData || {},
			IS_RELEASE: e.query.isRelease === 'true',
			PARENT_VERSION: e.query.parentVersion || '',
			PROJECT_ID: resource.PROJECT_ID,
			PROJECT_TITLE: resource.PROJECT_TITLE
		};

		// 创建版本
		const result = await this._resourceService.createVersion(data);

		if (!result) {
			return this.appError('创建版本失败');
		}

		return this.appReturn(result);
	}

	/**
	 * 创建资源快照
	 * @param {*} e 
	 */
	async createResourceSnapshot(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.projectId || !e.query.snapshotName) {
			return this.appError('项目ID和快照名称不能为空');
		}

		const projectId = e.query.projectId;
		const snapshotName = e.query.snapshotName;
		const snapshotDesc = e.query.snapshotDesc || '';

		// 创建快照
		const result = await this._resourceService.createResourceSnapshot(
			projectId, 
			snapshotName, 
			snapshotDesc
		);

		if (!result) {
			return this.appError('创建快照失败');
		}

		return this.appReturn(result);
	}

	/**
	 * 获取项目管理页面
	 * @param {*} e 
	 */
	async getResearchManagementPage(e) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.pageErrorAuth(err.message);
		}

		// 参数检查
		if (!e.query.id) {
			return this.pageError('项目ID不能为空');
		}

		const id = e.query.id;

		// 获取项目
		const project = await this._service.getResearchDetail(id);
		if (!project) {
			return this.pageError('项目不存在');
		}

		return this.render('projects/plm/pages/project/detail/project_detail', {
			project
		});
	}

	/**
	 * 获取项目状态路径
	 * @param {*} e 请求对象
	 */
	async getResearchStatePath(e) {
		try {
			// 验证权限
			this.isAdmin();
			
			// 参数检查
			if (!e.query.id) {
				return this.appError('项目ID不能为空');
			}
			
			const id = e.query.id;
			
			// 获取项目
			const project = await this._service.getResearchDetail(id);
			if (!project) {
				return this.appError('项目不存在');
			}
			
			// 获取项目流转历史记录
			const flowHistory = await this._service.getResearchFlowHistory(id);
			
			// 构建状态路径数据
			const statePath = [];
			
			// 基础状态节点
			const basicStates = [
				{ name: '项目立项', status: 'completed', desc: '项目创建阶段' },
				{ name: '需求确认', status: 'completed', desc: '需求分析与确认' },
				{ name: '方案设计', status: 'completed', desc: '技术方案设计' },
				{ name: '开发阶段', status: 'current', desc: '代码开发实现' },
				{ name: '测试验证', status: 'future', desc: '功能与性能测试' },
				{ name: '交付上线', status: 'future', desc: '项目交付与上线' },
				{ name: '运维支持', status: 'future', desc: '运维与客户支持' },
				{ name: '项目总结', status: 'future', desc: '经验总结与归档' }
			];
			
			// 根据项目状态设置路径节点状态
			const projectStatus = project.PROJECT_STATUS || 0;
			
			// 设置正确的当前状态
			let currentIndex = 0;
			if (projectStatus === 1) { // 初始状态
				currentIndex = 0;
			} else if (projectStatus === 2) { // 需求阶段
				currentIndex = 1;
			} else if (projectStatus === 3) { // 设计阶段
				currentIndex = 2;
			} else if (projectStatus === 4) { // 开发阶段
				currentIndex = 3;
			} else if (projectStatus === 5) { // 测试阶段
				currentIndex = 4;
			} else if (projectStatus === 6) { // 验收阶段
				currentIndex = 5;
			} else if (projectStatus >= 7) { // 完成/上线阶段
				currentIndex = 6;
			}
			
			// 更新状态节点状态
			for (let i = 0; i < basicStates.length; i++) {
				let node = { ...basicStates[i] };
				
				if (i < currentIndex) {
					node.status = 'completed';
				} else if (i === currentIndex) {
					node.status = 'current';
				} else {
					node.status = 'future';
				}
				
				// 添加流转历史信息
				if (flowHistory && flowHistory.list && flowHistory.list.length > 0) {
					// 尝试匹配流转记录
					const matchingFlow = flowHistory.list.find(flow => {
						return flow.STATUS_NAME && flow.STATUS_NAME.includes(node.name);
					});
					
					if (matchingFlow) {
						node.flowTime = matchingFlow.ADD_TIME_DISPLAY;
						node.flowNote = matchingFlow.FLOW_NOTE;
					}
				}
				
				statePath.push(node);
			}
			
			// 返回状态路径数据
			return this.appReturn({ data: statePath });
		} catch (err) {
			console.error('获取项目状态路径失败:', err);
			return this.appError('获取状态路径失败: ' + err.message);
		}
	}

	/**
	 * 获取研发项目列表数据
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async getResearchListData(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			const params = {
				search: req.query.search || '',
				sortType: req.query.sortType || '',
				status: req.query.status || '',
				mark: req.query.mark || '',
				userId: req.auth.openId
			};

			// 管理员可以看所有，普通用户只能看自己参与的
			if (!await AdminModel.isAdmin(req.auth.openId)) {
				params.isMyJoin = true;
			}

			const result = await ResearchService.getResearchList(params);
			
			// 格式化时间
			result.list = result.list.map(item => {
				item.RESEARCH_ADD_TIME_DESC = timeHelper.format(item.RESEARCH_ADD_TIME);
				item.RESEARCH_EDIT_TIME_DESC = timeHelper.format(item.RESEARCH_EDIT_TIME);
				
				// 状态描述和颜色
				item.RESEARCH_STATUS_NAME = researchBiz.getStateName(item.RESEARCH_STATUS);
				item.RESEARCH_STATUS_DESC = researchBiz.getStateDesc(item.RESEARCH_STATUS);
				item.RESEARCH_STATUS_COLOR = researchBiz.getStateColor(item.RESEARCH_STATUS);
				
				return item;
			});

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 获取研发项目详情
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async getResearchDetail(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 项目ID
			const id = req.params.id;
			if (!id) return pageHelper.error(res, '项目ID不存在');

			// 获取项目详情
			const result = await ResearchService.getResearchDetail(id);
			if (!result) return pageHelper.error(res, '项目不存在');

			// 增加浏览量
			await ResearchService.addViewCount(id);

			// 格式化时间
			result.RESEARCH_ADD_TIME_DESC = timeHelper.format(result.RESEARCH_ADD_TIME);
			result.RESEARCH_EDIT_TIME_DESC = timeHelper.format(result.RESEARCH_EDIT_TIME);
			
			// 状态信息
			result.RESEARCH_STATUS_NAME = researchBiz.getStateName(result.RESEARCH_STATUS);
			result.RESEARCH_STATUS_DESC = researchBiz.getStateDesc(result.RESEARCH_STATUS);
			result.RESEARCH_STATUS_COLOR = researchBiz.getStateColor(result.RESEARCH_STATUS);

			// 计算用户角色
			const userRole = await this._getUserRole(req.auth.openId, result);
			
			// 获取可用事件
			result.RESEARCH_EVENTS = researchBiz.getAvailableEvents(result.RESEARCH_STATUS, userRole);
			
			// 获取文档列表
			const docResult = await ResearchService.getDocumentList(id);
			result.RESEARCH_DOCS = docResult.list || [];
			
			// 获取操作记录
			const recordResult = await ResearchService.getRecordList(id);
			result.RESEARCH_RECORDS = recordResult.list || [];
			
			// 格式化记录时间
			result.RESEARCH_RECORDS = result.RESEARCH_RECORDS.map(item => {
				item.RECORD_ADD_TIME_DESC = timeHelper.format(item.RECORD_ADD_TIME, 'Y-M-D h:m:s');
				return item;
			});

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 添加研发项目
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async insertResearch(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 检查是否为管理员或经理
			const isAdmin = await AdminModel.isAdmin(req.auth.openId);
			if (!isAdmin) {
				return pageHelper.error(res, '只有管理员和经理才能创建项目');
			}

			// 获取表单数据
			const data = {
				RESEARCH_TITLE: req.body.title,
				RESEARCH_CONTENT: req.body.content,
				RESEARCH_START_DATE: req.body.startDate,
				RESEARCH_END_DATE: req.body.endDate,
				RESEARCH_TYPE: req.body.type,
				RESEARCH_PRIORITY: req.body.priority,
				RESEARCH_MANAGER_ID: req.body.managerId,
				RESEARCH_TEAM_MEMBER_IDS: req.body.teamMemberIds,
				RESEARCH_STATUS: researchBiz.STATES.PLANNING, // 初始状态为规划阶段
				RESEARCH_ADD_TIME: timeHelper.time(),
				RESEARCH_EDIT_TIME: timeHelper.time(),
				RESEARCH_ADD_USER_ID: req.auth.openId,
				RESEARCH_VIEW_CNT: 0,
			};

			// 插入数据库
			const result = await ResearchService.insertResearch(data);
			
			// 添加操作记录
			await ResearchService.addRecord(result.id, {
				action: '创建项目',
				content: `${userInfo.USER_NAME || '用户'}创建了项目`
			});

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 编辑研发项目
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async editResearch(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 项目ID
			const id = req.params.id;
			if (!id) return pageHelper.error(res, '项目ID不存在');

			// 获取项目详情
			const research = await ResearchService.getResearchDetail(id);
			if (!research) return pageHelper.error(res, '项目不存在');

			// 检查权限 (只有管理员、经理或创建者可以编辑)
			const isAdmin = await AdminModel.isAdmin(req.auth.openId);
			if (!isAdmin && research.RESEARCH_ADD_USER_ID !== req.auth.openId && 
					research.RESEARCH_MANAGER_ID !== req.auth.openId) {
				return pageHelper.error(res, '无权限编辑此项目');
			}

			// 获取表单数据
			const data = {
				RESEARCH_TITLE: req.body.title,
				RESEARCH_CONTENT: req.body.content,
				RESEARCH_START_DATE: req.body.startDate,
				RESEARCH_END_DATE: req.body.endDate,
				RESEARCH_TYPE: req.body.type,
				RESEARCH_PRIORITY: req.body.priority,
				RESEARCH_MANAGER_ID: req.body.managerId,
				RESEARCH_TEAM_MEMBER_IDS: req.body.teamMemberIds,
				RESEARCH_EDIT_TIME: timeHelper.time(),
			};

			// 更新数据库
			const result = await ResearchService.editResearch(id, data);
			
			// 添加操作记录
			await ResearchService.addRecord(id, {
				action: '编辑项目',
				content: `${userInfo.USER_NAME || '用户'}编辑了项目信息`
			});

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 删除研发项目
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async deleteResearch(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 项目ID
			const id = req.params.id;
			if (!id) return pageHelper.error(res, '项目ID不存在');

			// 获取项目详情
			const research = await ResearchService.getResearchDetail(id);
			if (!research) return pageHelper.error(res, '项目不存在');

			// 检查权限 (只有管理员或创建者可以删除)
			const isAdmin = await AdminModel.isAdmin(req.auth.openId);
			if (!isAdmin && research.RESEARCH_ADD_USER_ID !== req.auth.openId) {
				return pageHelper.error(res, '无权限删除此项目');
			}

			// 删除数据库记录
			const result = await ResearchService.deleteResearch(id);

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 执行状态事件
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async executeEvent(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) {
				return pageHelper.error(res, '用户不存在', { code: appCode.UNAUTHORIZED });
			}

			// 项目ID和事件ID
			const id = req.params.id;
			const eventId = req.body.eventId;
			
			if (!id) {
				return pageHelper.error(res, '项目ID不存在', { code: appCode.INVALID_PARAM });
			}
			if (!eventId) {
				return pageHelper.error(res, '事件ID不存在', { code: appCode.INVALID_PARAM });
			}

			// 获取项目详情
			const research = await ResearchService.getResearchDetail(id);
			if (!research) {
				return pageHelper.error(res, '项目不存在', { code: appCode.NOT_FOUND });
			}

			// 验证事件是否有效
			if (!researchBiz.isValidEvent(research.RESEARCH_STATUS, eventId)) {
				return pageHelper.error(res, '此状态下不允许执行该事件', { 
					code: appCode.FLOW_STATE_ERROR,
					data: {
						currentState: research.RESEARCH_STATUS,
						eventId: eventId,
						stateName: researchBiz.getStateName(research.RESEARCH_STATUS) 
					}
				});
			}

			// 获取用户角色
			const userRole = await this._getUserRole(req.auth.openId, research);
			
			// 获取当前状态可用事件
			const availableEvents = researchBiz.getAvailableEvents(research.RESEARCH_STATUS, userRole);
			
			// 检查用户是否有权限执行此事件
			const canExecute = availableEvents.some(e => e.id === eventId);
			if (!canExecute) {
				return pageHelper.error(res, '您没有权限执行此操作', { 
					code: appCode.FLOW_PERMISSION_ERROR,
					data: {
						userRole: userRole,
						requiredRole: researchBiz.getRequiredRoleForEvent(research.RESEARCH_STATUS, eventId)
					}
				});
			}

			// 获取目标状态
			const targetState = researchBiz.getTargetState(research.RESEARCH_STATUS, eventId);
			if (!targetState) {
				return pageHelper.error(res, '找不到目标状态', { 
					code: appCode.FLOW_STATE_ERROR,
					data: {
						currentState: research.RESEARCH_STATUS,
						eventId: eventId
					}
				});
			}

			// 验证必要文档是否已上传
			const researchDocument = require('../config/path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('research_document');
			const researchPhaseConfig = require('../config/path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('research_phase_config');
			
			// 获取当前状态所需必要文档
			const requiredDocs = researchPhaseConfig.getRequiredDocsByState(research.RESEARCH_STATUS);
			const requiredDocTypes = requiredDocs.filter(doc => doc.required).map(doc => doc.type);
			
			// 获取事件特定的必要文档
			const eventRequiredDocs = researchDocument.getRequiredDocumentsByEvent(eventId) || [];
			
			// 合并状态和事件所需的必要文档类型
			const allRequiredDocTypes = [...new Set([...requiredDocTypes, ...eventRequiredDocs])];
			
			// 如果有必要文档需求，则进行验证
			if (allRequiredDocTypes.length > 0) {
				// 获取项目已上传文档
				const docList = await ResearchService.getDocumentList(id, { cacheTime: 0 });
				
				// 提取文档类型
				let uploadedDocTypes = [];
				if (docList && docList.list && docList.list.length > 0) {
					// 提取文档类型字段，根据实际数据结构调整
					uploadedDocTypes = docList.list.map(doc => doc.DOCUMENT_TYPE || doc.DOC_TYPE);
				}
				
				// 检查是否缺少必要文档
				const missingDocs = allRequiredDocTypes.filter(type => !uploadedDocTypes.includes(type));
				if (missingDocs.length > 0) {
					const docNames = missingDocs.map(type => {
						return researchDocument.getDocumentTypeName(type) || type;
					}).join('、');
					
					return pageHelper.error(res, `状态转换前必须上传以下必要文档：${docNames}`, { 
						code: appCode.FLOW_DATA_ERROR,
						data: {
							missingDocs: missingDocs.map(type => ({
								type: type,
								name: researchDocument.getDocumentTypeName(type) || type
							}))
						}
					});
				}
			}

			// 表单数据
			const data = {
				RESEARCH_STATUS: targetState,
				RESEARCH_EDIT_TIME: timeHelper.time(),
			};

			// 获取事件名称
			const eventInfo = availableEvents.find(e => e.id === eventId);
			const eventName = eventInfo ? eventInfo.name : '状态变更';

			// 状态流转前拦截器（可添加额外验证逻辑）
			const beforeTransitResult = await this._beforeStateTransit(research, targetState, userInfo);
			if (beforeTransitResult !== true) {
				return pageHelper.error(res, beforeTransitResult.message || '状态转换失败', beforeTransitResult.data || {});
			}

			// 更新状态
			const result = await ResearchService.editResearch(id, data);
			
			// 添加操作记录
			await ResearchService.addRecord(id, {
				action: eventName,
				content: `${userInfo.USER_NAME || '用户'}将项目状态变更为"${researchBiz.getStateName(targetState)}"`,
				eventId: eventId,
				fromState: research.RESEARCH_STATUS,
				toState: targetState
			});

			// 状态流转后钩子（可以触发通知等）
			await this._afterStateTransit(research, targetState, userInfo);

			return pageHelper.success(res, result);
		} catch (err) {
			console.error('[executeEvent] 错误：', err);
			const errorCode = err.code || appCode.LOGIC;
			return pageHelper.error(res, err.message, { code: errorCode });
		}
	}

	/**
	 * 状态流转前拦截器
	 * @param {Object} research 项目信息
	 * @param {String} targetState 目标状态
	 * @param {Object} userInfo 用户信息
	 * @returns {Boolean|Object} 通过返回true，否则返回错误对象
	 * @private
	 */
	async _beforeStateTransit(research, targetState, userInfo) {
		// 可以根据需要添加特定业务逻辑校验
		return true;
	}

	/**
	 * 状态流转后处理
	 * @param {Object} research 项目信息
	 * @param {String} targetState 目标状态
	 * @param {Object} userInfo 用户信息
	 * @private
	 */
	async _afterStateTransit(research, targetState, userInfo) {
		// 可以添加状态变更后的处理逻辑，如发送通知等
		// TODO: 实现状态变更通知
	}

	/**
	 * 上传文档
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async uploadDocument(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 项目ID
			const id = req.params.id;
			if (!id) return pageHelper.error(res, '项目ID不存在');

			// 获取项目详情
			const research = await ResearchService.getResearchDetail(id);
			if (!research) return pageHelper.error(res, '项目不存在');

			// 获取用户角色，检查权限
			const userRole = await this._getUserRole(req.auth.openId, research);
			if (userRole === 'viewer') {
				return pageHelper.error(res, '您没有权限上传文档');
			}

			// 获取文件信息
			const fileId = req.body.fileId;
			const fileName = req.body.fileName;
			const fileUrl = req.body.fileUrl;
			
			if (!fileId || !fileName || !fileUrl) {
				return pageHelper.error(res, '文件信息不完整');
			}

			// 上传文档
			const result = await ResearchService.uploadDocument(id, fileId, fileName, fileUrl);
			
			// 添加操作记录
			await ResearchService.addRecord(id, {
				action: '上传文档',
				content: `${userInfo.USER_NAME || '用户'}上传了文档"${fileName}"`
			});

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 删除文档
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async deleteDocument(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 文档ID和项目ID
			const id = req.params.id;
			const researchId = req.query.researchId;
			
			if (!id) return pageHelper.error(res, '文档ID不存在');
			if (!researchId) return pageHelper.error(res, '项目ID不存在');

			// 获取项目详情
			const research = await ResearchService.getResearchDetail(researchId);
			if (!research) return pageHelper.error(res, '项目不存在');

			// 获取用户角色，检查权限
			const userRole = await this._getUserRole(req.auth.openId, research);
			if (userRole === 'viewer') {
				return pageHelper.error(res, '您没有权限删除文档');
			}

			// 删除文档
			const result = await ResearchService.deleteDocument(id, researchId);
			
			// 添加操作记录
			await ResearchService.addRecord(researchId, {
				action: '删除文档',
				content: `${userInfo.USER_NAME || '用户'}删除了一个文档`
			});

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 获取文档列表
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async getDocumentList(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 项目ID
			const researchId = req.query.researchId;
			if (!researchId) return pageHelper.error(res, '项目ID不存在');

			// 获取文档列表
			const result = await ResearchService.getDocumentList(researchId);

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 获取操作记录列表
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async getRecordList(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 项目ID
			const researchId = req.query.researchId;
			if (!researchId) return pageHelper.error(res, '项目ID不存在');

			// 获取操作记录
			const result = await ResearchService.getRecordList(researchId);
			
			// 格式化记录时间
			if (result && result.list) {
				result.list = result.list.map(item => {
					item.RECORD_ADD_TIME_DESC = timeHelper.format(item.RECORD_ADD_TIME, 'Y-M-D h:m:s');
					return item;
				});
			}

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 添加操作记录
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async addRecord(req, res) {
		try {
			// 获取用户信息
			const userInfo = await UserModel.getOne(req.auth.openId);
			if (!userInfo) return pageHelper.error(res, '用户不存在');

			// 项目ID
			const researchId = req.body.researchId;
			if (!researchId) return pageHelper.error(res, '项目ID不存在');

			// 获取记录数据
			const data = {
				action: req.body.action || '操作',
				content: req.body.content || '进行了操作',
				userId: req.auth.openId,
				userName: userInfo.USER_NAME || '用户'
			};

			// 添加记录
			const result = await ResearchService.addRecord(researchId, data);

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 增加项目访问数
	 * @param {*} req 请求对象
	 * @param {*} res 响应对象
	 */
	async addViewCount(req, res) {
		try {
			// 项目ID
			const id = req.body.id;
			if (!id) return pageHelper.error(res, '项目ID不存在');

			// 增加访问量
			const result = await ResearchService.addViewCount(id);

			return pageHelper.success(res, result);
		} catch (err) {
			return pageHelper.error(res, err.message);
		}
	}

	/**
	 * 获取用户在项目中的角色
	 * @private
	 */
	async _getUserRole(userId, research) {
		// 检查是否为管理员
		const isAdmin = await AdminModel.isAdmin(userId);
		if (isAdmin) {
			return 'admin';
		}
		
		// 检查是否为项目经理
		if (research.RESEARCH_MANAGER_ID === userId) {
			return 'manager';
		}
		
		// 检查是否为开发成员
		if (Array.isArray(research.RESEARCH_TEAM_MEMBER_IDS) && 
				research.RESEARCH_TEAM_MEMBER_IDS.includes(userId)) {
			return 'developer';
		}
		
		// 其他角色为查看者
		return 'viewer';
	}

	/**
	 * 批量删除资源
	 * @param {*} req 
	 * @param {*} res 
	 */
	async deleteResourceBatch(req, res) {
		try {
			this.isAdmin();
		} catch (err) {
			return this.appErrorAuth(err.message);
		}

		// 参数检查
		if (!req.body.idList || !Array.isArray(req.body.idList) || req.body.idList.length === 0) {
			return this.appError('资源ID列表不能为空');
		}

		const idList = req.body.idList;

		// 批量删除资源
		const result = await this._resourceService.deleteResourceBatch(idList);

		return this.appReturn({
			deleted: result.deleted,
			count: result.count
		});
	}
}

module.exports = ResearchController; 